package com.example.jdai.jdai.ui;

import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.example.jdai.jdai.R;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by hellopyj on 2017/1/5.
 */

public class TopBar extends RelativeLayout {

    @BindView(R.id.bt_back)
    Button btBack;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.bt_more)
    Button btMore;
    TopBarLisener topBarLisener = null;
    @BindView(R.id.bt_left)
    Button btLeft;

    public TopBar(Context context) {
        super(context);
        init(context, null);
    }

    public TopBar(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init(context, attrs);
    }

    public TopBar(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context, attrs);
    }

    void init(Context context, AttributeSet attrs) {
        TypedArray ts = context.obtainStyledAttributes(attrs, R.styleable.TopBar);
        String title = ts.getString(R.styleable.TopBar_titleName);
        String right_text = ts.getString(R.styleable.TopBar_righttext);
        String left_text = ts.getString(R.styleable.TopBar_lefttext);
        int vi = ts.getInt(R.styleable.TopBar_rightvisable, 0);
        int lvi = ts.getInt(R.styleable.TopBar_leftvisable, 0);
        LayoutInflater.from(context).inflate(R.layout.top_bar, this);
        ButterKnife.bind(this);
        if (title != null)
            tvTitle.setText(title);
        if (right_text != null)
            btMore.setText(right_text);

        btMore.setVisibility(vi);
        btBack.setVisibility(lvi);
        if (left_text != null) {
            btBack.setVisibility(GONE);
            btLeft.setVisibility(VISIBLE);
            btLeft.setText(left_text);

        }
        ts.recycle();


    }

    @OnClick({R.id.bt_back})
    void onback() {
        if (topBarLisener != null)
            topBarLisener.back();
    }

    @OnClick(R.id.bt_more)
    void onmore() {
        if (topBarLisener != null)
            topBarLisener.more();
    }

    void setTitle(String title) {
        tvTitle.setText(title);
    }

    public void disToggleRightVisable() {
        if (btMore.getVisibility() == VISIBLE) {
            btMore.setVisibility(INVISIBLE);
        } else {
            btMore.setVisibility(VISIBLE);
        }
    }


    @OnClick(R.id.bt_left)
    public void onClick() {
        if (topBarLisener != null)
            topBarLisener.back();

    }

    public interface TopBarLisener {
        void back();

        void more();

    }

    public void setTopBarLisener(TopBarLisener topBarLisener) {
        this.topBarLisener = topBarLisener;
    }
}
